package com.ljfiction.book.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.AlphaAnimation;
import android.view.animation.AnimationSet;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.ljfiction.book.Baner.ShouCangBookBean;
import com.ljfiction.book.Baner.ShujiaTuijianBookBean;
import com.ljfiction.book.Baner.SinginBean;
import com.ljfiction.book.MyView.GlideImageLoader;
import com.ljfiction.book.R;
import com.ljfiction.book.activitys.LoginActivity;
import com.ljfiction.book.activitys.MainActivity;
import com.ljfiction.book.activitys.Reading2Activity;
import com.ljfiction.book.http.HttpManager;
import com.ljfiction.book.http.UserManageBean;
import com.ljfiction.book.myinterface.Mainlistener;
import com.ljfiction.book.tools.SettingManager;
import com.ljfiction.book.tools.TimeTool;
import com.lzy.okhttputils.OkHttpUtils;
import com.lzy.okhttputils.callback.StringCallback;
import com.lzy.okhttputils.request.BaseRequest;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.youth.banner.Banner;
import com.zhy.autolayout.utils.AutoUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Call;
import okhttp3.Response;


public class BookshelfFragment extends BaseFragment {

    @BindView(R.id.daohanglan_bookshelf)
    LinearLayout daohanglanBookshelf;


    Unbinder unbinder;


    @BindView(R.id.siginlayout)
    RelativeLayout siginlayout;
    @BindView(R.id.gridView_bookshelf)
    RecyclerView gridViewBookshelf;
    @BindView(R.id.down_bookshelf)
    TextView downBookshelf;
    @BindView(R.id.nowread)
    TextView nowread;

    @BindView(R.id.dibucaozuo)
    LinearLayout dibucaozuo;
    @BindView(R.id.giveImage)
    ImageView giveImage;
    @BindView(R.id.giveimagevisibily)
    LinearLayout giveimagevisibily;
    @BindView(R.id.recycle_sigin)
    RecyclerView recycleSigin;
    @BindView(R.id.refresh_bookshelf)
    SmartRefreshLayout refreshBookshelf;
    @BindView(R.id.bannerview_bookshelf)
    Banner bannerviewBookshelf;
    @BindView(R.id.nobooks_bookshelf)
    LinearLayout nobooksBookshelf;
    private Context context;
    private ShouCangBookBean.DataBean.ListBean addbook;
    private List<ShouCangBookBean.DataBean.ListBean> booklist = new ArrayList<>();
    private BaseQuickAdapter adpter;
    private ShouCangBookBean shouCangBookBean;
    private int today = 0;
    private SinginBean singinBean;
    private BaseQuickAdapter singinAdapter;
    private List<SinginBean.DataBean> dataBean = new ArrayList<>();
    private Intent intent;
    public static boolean isbianji = false;
    private List<String> selectList = new ArrayList<>();
    private List<ShujiaTuijianBookBean.DataBean> tuijianListBook = new ArrayList<>();
    private ShujiaTuijianBookBean shuajiatuijain;
    private Mainlistener mainlistener;
    private String[] zhouji = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
    private boolean isgetDataOver = false, isgetDataOver2 = false;//防止网络重复请求

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_bookshelf, container, false);
        context = getActivity();
        unbinder = ButterKnife.bind(this, view);
        intent = new Intent(context, Reading2Activity.class);
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) daohanglanBookshelf.getLayoutParams();
        //获取当前控件的布局对象
        params.height = MainActivity.getStatusBarHeight(context);//设置当前控件布局的高度
        daohanglanBookshelf.setLayoutParams(params);//将设置好的布局参数应用到控件中
        addbook = new ShouCangBookBean.DataBean.ListBean();


        intView();
        getXingqiji();
        initDataBook();
        inttuijianBook();
        return view;
    }

    private void inttuijianBook() {
        OkHttpUtils.post(HttpManager.IP + "/bookshelf-recommendPosition")
                .params("version", "2.0")
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        refreshBookshelf.finishRefresh();
                        Gson g = new Gson();
                        try {
                            shuajiatuijain = g.fromJson(s, ShujiaTuijianBookBean.class);
                            if (shuajiatuijain.getReturnCode() == 200) {
                                tuijianListBook.clear();
                                tuijianListBook.addAll(shuajiatuijain.getData());
                                bannerviewBookshelf.update(tuijianListBook);
                            }

                        } catch (JsonSyntaxException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    //如果你需要考虑更好的体验，可以这么操作
    @Override
    public void onStart() {
        super.onStart();
        //开始轮播
        bannerviewBookshelf.startAutoPlay();
    }

    @Override
    public void onStop() {
        super.onStop();
        //结束轮播
        bannerviewBookshelf.stopAutoPlay();
    }

    private void initDataBook() {
        if (UserManageBean.isLogin()) {
            OkHttpUtils.post(HttpManager.IP + "/bookshelf-getuserbookshelf")
                    .params("userid", String.valueOf(UserManageBean.userBean.getUserId()))
                    .execute(new StringCallback() {
                        @Override
                        public void onBefore(BaseRequest request) {
                            super.onBefore(request);

                        }

                        @SuppressLint("SetTextI18n")
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            isgetDataOver = false;
                            refreshBookshelf.finishRefresh();
                            Gson gson = new Gson();
                            try {
                                shouCangBookBean = gson.fromJson(s, ShouCangBookBean.class);
                                booklist.clear();
                                if (shouCangBookBean.getReturnCode() == 200) {
                                    booklist.addAll(shouCangBookBean.getData().getList());
                                }
                                if (booklist.size()>0){
                                    nowread.setVisibility(View.VISIBLE);
                                    nobooksBookshelf.setVisibility(View.GONE);
                                    gridViewBookshelf.setVisibility(View.VISIBLE);
                                    nowread.setText("正在阅读(" + booklist.size() + ")");
                                    booklist.add(addbook);
                                    adpter.notifyDataSetChanged();
                                }else {
                                    nowread.setVisibility(View.GONE);
                                    gridViewBookshelf.setVisibility(View.GONE);
                                    nobooksBookshelf.setVisibility(View.VISIBLE);
                                }

                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    });
        } else {
            booklist.clear();
            nowread.setVisibility(View.GONE);
            gridViewBookshelf.setVisibility(View.GONE);
            nobooksBookshelf.setVisibility(View.VISIBLE);
        }
    }

    private void intView() {
        bannerviewBookshelf.setImageLoader(new GlideImageLoader())
                .setOnBannerListener(position -> {
                    if (tuijianListBook.get(position).getShowHide() == 0) {
                        Intent intent = new Intent(context, Reading2Activity.class);
                        intent.putExtra("bookId", String.valueOf(tuijianListBook.get(position).getBookId()));
                        startActivity(intent);
                    } else {
                        Intent intent = new Intent();
                        intent.setAction("android.intent.action.VIEW");
                        Uri content_url = Uri.parse(tuijianListBook.get(position).getDetailsImgAndPageURL());
                        intent.setData(content_url);
                        startActivity(intent);
                    }

                })
                .start();
        gridViewBookshelf.setAdapter(adpter = new BaseQuickAdapter<ShouCangBookBean.DataBean.ListBean, BaseViewHolder>(R.layout.shujiaitem, booklist) {
            @Override
            protected void convert(BaseViewHolder helper, ShouCangBookBean.DataBean.ListBean item) {
                AutoUtils.autoSize(helper.itemView);
                if (helper.getLayoutPosition() == booklist.size() - 1) {
                    Glide.with(mContext).load(R.drawable.addbook).into((ImageView) helper.getView(R.id.shujiabookimage));
                    helper.getView(R.id.isselect).setVisibility(View.GONE);
                    helper.getView(R.id.iswanjie).setVisibility(View.GONE);
                    helper.setText(R.id.shujiabookname, "")
                            .setText(R.id.shujiabookgettime, "");
                } else {
                    helper.getView(R.id.iswanjie).setVisibility(View.VISIBLE);
                    Glide.with(mContext).load(item.getBookImage()).into((ImageView) helper.getView(R.id.shujiabookimage));
                    helper.setText(R.id.shujiabookname, item.getBookName())
                            .setText(R.id.shujiabookgettime, TimeTool.getDateTime(item.getLastUpdateTime()));

                    if (item.getNewIndex() == 0) {
                        helper.getView(R.id.iswanjie).setVisibility(View.GONE);
                    } else {
                        helper.getView(R.id.iswanjie).setVisibility(View.VISIBLE);
                    }
                    if (BookshelfFragment.isbianji) {
                        helper.getView(R.id.isselect).setVisibility(View.VISIBLE);
                        if (item.isSelect()) {
                            ((ImageView) helper.getView(R.id.isselect)).setImageResource(R.mipmap.done);
                        } else {
                            ((ImageView) helper.getView(R.id.isselect)).setImageResource(R.mipmap.none);
                        }
                    } else {
                        helper.getView(R.id.isselect).setVisibility(View.GONE);
                    }
                    if (item.getBookStatus() == 1) {
                        helper.setText(R.id.isoverl, "  已完结").setTextColor(R.id.isoverl, Color.parseColor("#FB5E6F"));
                    } else {
                        helper.setText(R.id.isoverl, "  连载中").setTextColor(R.id.isoverl, Color.parseColor("#47B2D8"));
                    }
                }

            }
        });
        adpter.setOnItemClickListener((adapter, view, position) -> {
            if (isbianji) {
                if (booklist.get(position).isSelect()) {
                    booklist.get(position).setSelect(false);
                } else {
                    booklist.get(position).setSelect(true);
                }
                adapter.notifyDataSetChanged();

            } else {
                if (position == booklist.size() - 1) {
                    mainlistener.tohom();
                    return;
                }
                intent.putExtra("bookId", String.valueOf(booklist.get(position).getBookId()));
                startActivity(intent);
            }

        });


        gridViewBookshelf.setLayoutManager(new GridLayoutManager(context, 3));


        recycleSigin.setAdapter(singinAdapter = new BaseQuickAdapter<SinginBean.DataBean, BaseViewHolder>(R.layout.siginitem, dataBean) {
            @Override
            protected void convert(BaseViewHolder helper, SinginBean.DataBean item) {
                switch (item.getValues()) {
                    case "0":
                        ((ImageView) helper.getView(R.id.singinitemimage)).setImageResource(R.mipmap.ovalno);
                        break;
                    case "1":
                        ((ImageView) helper.getView(R.id.singinitemimage)).setImageResource(R.mipmap.ovalcopyyes);
                        break;
                    case "2":
                        ((ImageView) helper.getView(R.id.singinitemimage)).setImageResource(R.mipmap.ovalcopy);
                        break;
                    case "3":
                        ((ImageView) helper.getView(R.id.singinitemimage)).setImageResource(R.mipmap.ovalcopyno);
                        break;
                }
                helper.setText(R.id.xingqiji, zhouji[helper.getLayoutPosition()]);
            }
        });
        recycleSigin.setLayoutManager(new GridLayoutManager(context, 7));

        refreshBookshelf.setEnableLoadMore(false);
        refreshBookshelf.setOnRefreshListener(refreshlayout -> {
            getXingqiji();
            initDataBook();
            inttuijianBook();
        });
    }


    private void initData() {
        OkHttpUtils.get(HttpManager.IP + "/user-signinstate")

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        isgetDataOver2 = false;
                        refreshBookshelf.finishRefresh();
                        Gson gson = new Gson();
                        try {
                            singinBean = gson.fromJson(s, SinginBean.class);
                            if (singinBean.getReturnCode() == 200) {
                                siginlayout.setVisibility(View.GONE);
                            } else if (singinBean.getReturnCode() == 700) {
                                dataBean.clear();
                                siginlayout.setVisibility(View.VISIBLE);
                                dataBean.addAll(singinBean.getData());
                                singinAdapter.notifyDataSetChanged();
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });

    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.down_bookshelf, R.id.immediately, R.id.taball, R.id.delet, R.id.giveimagevisibily,R.id.nobooks_bookshelf})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.down_bookshelf:
                if (booklist.size()<1){
                    showToast("书架里还没有添加书籍哦！");
                    return;
                }

                if (isbianji) {
                    isbianji = false;
                    mainlistener.showbottom();
                    dibucaozuo.setVisibility(View.INVISIBLE);
                    for (ShouCangBookBean.DataBean.ListBean i :
                            booklist) {
                        i.setSelect(false);
                    }
                    downBookshelf.setText("编辑");
                    adpter.notifyDataSetChanged();

                } else {
                    isbianji = true;
                    mainlistener.hidebottom();
                    dibucaozuo.setVisibility(View.VISIBLE);
                    downBookshelf.setText("取消");
                    adpter.notifyDataSetChanged();
                }

                break;
            case R.id.immediately:

                if (!UserManageBean.isLogin(context)) {
                    return;
                } else {
                    toSingin();
                }
                break;
            case R.id.taball:
                for (ShouCangBookBean.DataBean.ListBean i :
                        booklist) {
                    i.setSelect(true);
                }
                adpter.notifyDataSetChanged();
                break;
            case R.id.delet:
                todeletBook();
                break;
            case R.id.giveimagevisibily:
                if (giveimagevisibily.getVisibility() == View.VISIBLE) {
                    giveimagevisibily.setVisibility(View.GONE);
                    AnimationSet aset1 = new AnimationSet(true);
                    AlphaAnimation aa1 = new AlphaAnimation(1, 0);
                    aa1.setDuration(1000);
                    aset1.addAnimation(aa1);
                    giveimagevisibily.startAnimation(aset1);

                }
                break;
            case R.id.nobooks_bookshelf:
                mainlistener.tohom();
                break;
        }
    }

    private void todeletBook() {
        selectList.clear();
        for (int i = 0; i < booklist.size() - 1; i++) {
            if (booklist.get(i).isSelect()) {
                selectList.add(String.valueOf(booklist.get(i).getId()));
            }
        }
        if (selectList.size() < 1) {
            showToast("请选择要删除的书籍");
            return;
        }
        OkHttpUtils.post(HttpManager.IP + "/bookshelf-deluserbookshelf")

                .params("id", selectList.toString().substring(1, selectList.toString().length() - 1))
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject js = new JSONObject(s);
                            if (js.getInt("returnCode") == 200) {
                                Toast.makeText(context, js.getString("msg"), Toast.LENGTH_SHORT).show();
                                isbianji = false;
                                dibucaozuo.setVisibility(View.INVISIBLE);
                                mainlistener.showbottom();
                                downBookshelf.setText("编辑");
                                initDataBook();
                            } else {
                                showToast(js.getString("msg"));
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                });
    }


    private void toSingin() {
        OkHttpUtils.post(HttpManager.IP + "/user-signin")

                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        try {
                            JSONObject jsonObject = new JSONObject(s);
                            if (jsonObject.getInt("returnCode") == 200) {
                                siginlayout.setVisibility(View.GONE);
                                giveimagevisibily.setVisibility(View.VISIBLE);
                                // giveImage.startAnimation(animation);
                                AnimationSet aset = new AnimationSet(true);
                                AlphaAnimation aa = new AlphaAnimation(0, 1);
                                aa.setDuration(1000);
                                aset.addAnimation(aa);
                                giveImage.startAnimation(aset);
                            } else if (jsonObject.getInt("returnCode") == 800) {
                                siginlayout.setVisibility(View.GONE);
                                giveimagevisibily.setVisibility(View.GONE);
                                showToast(jsonObject.getString("msg"));
                            } else if (jsonObject.getInt("returnCode") == 400) {
                                Intent intent = new Intent(context, LoginActivity.class);
                                startActivity(intent);
                                showToast(jsonObject.getString("msg"));
                            }

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                });
    }

    //   private Long ld = null;

    private void getXingqiji() {
        dataBean.clear();

        Date date = new Date(System.currentTimeMillis());// 转换为标准时间对象
        @SuppressLint("SimpleDateFormat") SimpleDateFormat format = new SimpleDateFormat("EEEE");
        toXInqingji(format.format(date));

    }

    private void toXInqingji(String xingqiji) {
        switch (xingqiji) {
            case "星期一":
                today = 0;
                break;
            case "星期二":
                today = 1;
                break;
            case "星期三":
                today = 2;
                break;
            case "星期四":
                today = 3;
                break;
            case "星期五":
                today = 4;
                break;
            case "星期六":
                today = 5;
                break;
            case "星期日":
                today = 6;
            case "Monday":
                today = 0;
                break;
            case "Tuesday":
                today = 1;
                break;
            case "Wednesday":
                today = 2;
                break;
            case "Thursday":
                today = 3;
                break;
            case "Friday":
                today = 4;
                break;
            case "Saturday":
                today = 5;
                break;
            case "Sunday":
                today = 6;
                break;

        }
        if (UserManageBean.isLogin()) {
            initData();
        } else {
            for (int i = 0; i < 7; i++) {
                SinginBean.DataBean dataBean1 = new SinginBean.DataBean();
                dataBean.add(dataBean1);
                if (i < today) {
                    dataBean1.setValues("0");
                } else if (i == today) {
                    dataBean1.setValues("2");
                } else {
                    dataBean1.setValues("3");
                }

            }
            siginlayout.setVisibility(View.VISIBLE);
            singinAdapter.notifyDataSetChanged();
        }

    }


    @Override
    public void onPause() {
        super.onPause();
    }


    @Override
    public void onResume() {
        super.onResume();
        if (adpter != null) {
            if (!isgetDataOver) {
                initDataBook();
                isgetDataOver = true;
            }

            //inttuijianBook();
        }
        if (singinAdapter != null) {
            if (!isgetDataOver2) {
                getXingqiji();
                isgetDataOver2 = true;
            }

        }


    }


    public BookshelfFragment setMainlistener(Mainlistener mainlistener) {
        this.mainlistener = mainlistener;
        return this;
    }
}
